//
//  FSBaseViewController.m
//  FSScrollViewNestTableViewDemo
//
//  Created by huim on 2017/5/23.
//  Copyright © 2017年 fengshun. All rights reserved.
//

#import "FSBaseViewController.h"
#import "FSBaseTableView.h"
#import "FSPageContentView.h"
#import "FSSegmentTitleView.h"
#import "FSScrollContentViewController.h"
#import "FSBottomTableViewCell.h"


#import "HomeCycleImageCell.h"
#import "ADImageTableCell.h"
#import "HomeProgramaCell.h"
#import "HomeNoticeCell.h"
#import "GoodDetailController.h"
#import "GoodsCategoryVC.h"

#import "HomeDataModel.h"
#import "HomeADModel.h"
#import "HomeNavModel.h"
#import "GoodsInfoModel.h"

#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
@interface FSBaseViewController ()<UITableViewDelegate,UITableViewDataSource,FSPageContentViewDelegate,FSSegmentTitleViewDelegate>
@property (nonatomic, strong) FSBaseTableView *tableView;
@property (nonatomic, strong) FSBottomTableViewCell *contentCell;
@property (nonatomic, strong) FSSegmentTitleView *titleView;
@property (nonatomic, assign) BOOL canScroll;

@property (nonatomic, strong) HomeDataModel *homeData;
@end

@implementation FSBaseViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Alipay" style:UIBarButtonItemStylePlain target:self action:@selector(alipay)];
    
       self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"WXPay" style:UIBarButtonItemStylePlain target:self action:@selector(testPay)];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeScrollStatus) name:@"leaveTop" object:nil];
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    if (@available(iOS 11.0, *)) {
        
        self.tableView.estimatedRowHeight = 200;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
        
        
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
    }
    
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([HomeCycleImageCell class]) bundle:nil] forCellReuseIdentifier:[HomeCycleImageCell identifierStr]];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ADImageTableCell class]) bundle:nil] forCellReuseIdentifier:[ADImageTableCell identifierStr]];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([HomeProgramaCell class]) bundle:nil] forCellReuseIdentifier:[HomeProgramaCell identifierStr]];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([HomeNoticeCell class]) bundle:nil] forCellReuseIdentifier:[HomeNoticeCell identifierStr]];
    
    
    
    self.tableView.contentInset = UIEdgeInsetsMake(IPhoneX ? 88 : 64, 0, IPhoneX ? 83 : 49, 0);
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.canScroll = YES;
    
    MJWeakSelf
    self.tableView.mj_header = [XMGRefreshHeader headerWithRefreshingBlock:^{
        
        
        [weakSelf loadData];
        
    }];
    
    [self.tableView.mj_header beginRefreshing];
    
   
}

- (void)alipay{
    
    
    NSMutableDictionary *parmars = [[NSMutableDictionary alloc]init];
    parmars[@"recharge_money"] =  @"20";
    parmars[@"payment_code"] =  @"alipay";
    parmars[@"user_no"] =  @"10005";
    
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"index.php/Api/Member/add_recharge" parameters:parmars completionHandler:^(id responseObject, NSError *error) {
        if (!error) {
                        MYJSONSTR
            
            [self alipayWithDic:responseObject[@"data"][@"alipay_string"]];
            
        }else{
            
 
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
    }];
    
    
    

}


- (void)alipayWithDic:(NSString *)str{
    
    
    [[AlipaySDK defaultService] payOrder:str fromScheme:@"com.beisheng.fengqiang" callback:^(NSDictionary *resultDic) {
        
        NSLog(@"reslut = %@",resultDic);
        
    }];
    
    
    
}


- (void)testPay{
    
    NSMutableDictionary *parmars = [[NSMutableDictionary alloc]init];
    parmars[@"recharge_money"] =  @"20";
    parmars[@"payment_code"] =  @"wxpay";
    parmars[@"user_no"] =  @"10005";
    
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"index.php/Api/Member/add_recharge" parameters:parmars completionHandler:^(id responseObject, NSError *error) {
        if (!error) {
            
//            MYJSONSTR
            
            [self WXPayWithDic:responseObject[@"data"][@"wxpay_params"]];
            
        }else{
            
            [SVProgressHUD showInfoWithStatus:error.domain];

            
        }
        
    }];
    
    
    
    
}


- (void)WXPayWithDic:(NSDictionary *)dic{
    
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
    req.openID = dic[@"appid"];
    
    // 商家id，在注册的时候给的
    req.partnerId = dic[@"partnerid"];
    
    // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
    req.prepayId  = dic[@"prepayid"];
    
    // 根据财付通文档填写的数据和签名
    //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
    req.package   = dic[@"pkg"];
    
    // 随机编码，为了防止重复的，在后台生成
    req.nonceStr  = dic[@"noncestr"];
    
    // 这个是时间戳，也是在后台生成的，为了验证支付的
    NSString * stamp = dic[@"timestamp"];
    
    req.timeStamp = stamp.intValue;
    
    // 这个签名也是后台做的
    req.sign = dic[@"sign"];
    
    //发送请求到微信，等待微信返回onResp
    [WXApi sendReq:req];
}



- (void)loadData{
    
    
    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"index.php/Api/Dbindex/index" parameters:nil completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
//            [responseObject[@"data"][@"record_list"][0] propertyCode];

            weakSelf.homeData = [HomeDataModel mj_objectWithKeyValues:responseObject[@"data"]];
            
            [weakSelf.tableView.mj_header endRefreshing];
            
            [weakSelf.tableView reloadData];
            
        } else {
            
            [weakSelf.tableView.mj_header endRefreshing];
            
            [SVProgressHUD showErrorWithStatus:error.domain];
        }
        
    }];
    
    
}






- (void)insertRowAtTop
{
    NSArray *sortTitles = @[@"人气",@"最新",@"进度",@"总需人次"];
    self.contentCell.currentTagStr = sortTitles[self.titleView.selectIndex];
    self.contentCell.isRefresh = YES;
    [self.tableView.mj_header endRefreshing];
}

#pragma mark notify
- (void)changeScrollStatus//改变主视图的状态
{
    self.canScroll = YES;
    self.contentCell.cellCanScroll = NO;
}

#pragma mark UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.homeData == nil) {
        return 0;
    }
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.homeData == nil) {
        return 0;
    }
    
    if (section == 0) {
        return 4;
    } else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            return  KScreenW / 69.0 * 28.0 + 16;
            
        } else if (indexPath.row == 1){
            
            return  130;
            
            
        }else if (indexPath.row == 2){
            
            return  108;
            
            
        }else{
            
            return  54;
            
            
        }
        
    }else{
        
         return  KScreenH - (IPhoneX ? 88 : 64);
        
        
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 36;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0;
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    
    if (section == 1) {
        
      return self.titleView;
        
    } else {
        
        return [[UIView alloc]init];
    }

   
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return [[UIView alloc]init];
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            HomeCycleImageCell *cell = [tableView dequeueReusableCellWithIdentifier:[HomeCycleImageCell identifierStr]];
            cell.urls = [self.homeData.multi_adv valueForKeyPath:@"adv_image"];
            return  cell;
        } else if (indexPath.row == 1) {
            
            ADImageTableCell *cell = [tableView dequeueReusableCellWithIdentifier:[ADImageTableCell identifierStr]];
            cell.model = self.homeData.single_adv;
            return  cell;
            
        }else if (indexPath.row == 2) {
            
            HomeProgramaCell *cell = [tableView dequeueReusableCellWithIdentifier:[HomeProgramaCell identifierStr]];
            cell.models = self.homeData.nav_list;
            return  cell;
            
        }else{
            
            HomeNoticeCell *cell = [tableView dequeueReusableCellWithIdentifier:[HomeNoticeCell identifierStr]];
            cell.models = self.homeData.record_list;
            return cell;
            
        }
        
    }else{
        
        _contentCell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        if (!_contentCell) {
            _contentCell = [[FSBottomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            NSArray *titles = @[@"人气",@"最新",@"进度",@"总需人次"];
            NSMutableArray *contentVCs = [NSMutableArray array];
            for (NSString *title in titles) {
                FSScrollContentViewController *vc = [[FSScrollContentViewController alloc]init];
                vc.title = title;
                vc.str = title;
                [contentVCs addObject:vc];
            }
            _contentCell.viewControllers = contentVCs;
            _contentCell.pageContentView = [[FSPageContentView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, KScreenH - (IPhoneX ? 88 : 64) - 36) childVCs:contentVCs parentVC:self delegate:self];
            [_contentCell.contentView addSubview:_contentCell.pageContentView];
        }
        return _contentCell;
        
        
        
    }


}

#pragma mark FSSegmentTitleViewDelegate
- (void)FSContenViewDidEndDecelerating:(FSPageContentView *)contentView startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex
{
    self.titleView.selectIndex = endIndex;
    _tableView.scrollEnabled = YES;//此处其实是监测scrollview滚动，pageView滚动结束主tableview可以滑动，或者通过手势监听或者kvo，这里只是提供一种实现方式
}

- (void)FSSegmentTitleView:(FSSegmentTitleView *)titleView startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex
{
    self.contentCell.pageContentView.contentViewCurrentIndex = endIndex;
}

- (void)FSContentViewDidScroll:(FSPageContentView *)contentView startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex progress:(CGFloat)progress
{
    _tableView.scrollEnabled = NO;//pageView开始滚动主tableview禁止滑动
}

#pragma mark UIScrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (self.homeData == nil) {
        return;
    }
    
    CGFloat bottomCellOffset = [_tableView rectForSection:1].origin.y - 64;
    if (scrollView.contentOffset.y >= bottomCellOffset) {
        scrollView.contentOffset = CGPointMake(0, bottomCellOffset);
        if (self.canScroll) {
            self.canScroll = NO;
            self.contentCell.cellCanScroll = YES;
        }
    }else{
        if (!self.canScroll) {//子视图没到顶部
            scrollView.contentOffset = CGPointMake(0, bottomCellOffset);
        }
    }
    
//    self.tableView.showsVerticalScrollIndicator = _vcCanScroll?YES:NO;
    
}

#pragma mark LazyLoad
- (FSBaseTableView *)tableView
{
    if (!_tableView) {
        _tableView = [[FSBaseTableView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        _tableView.bounces = NO;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}



- (FSSegmentTitleView *)titleView{
    
    if (!_titleView) {
        
        _titleView = [[FSSegmentTitleView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, 36) titles:@[@"人气",@"最新",@"进度",@"总需人次"] delegate:self indicatorType:FSIndicatorTypeEqualTitle];
        
        UIView *underline = [[UIView alloc] init];
        CGFloat underlineH = 0.5;
        underline.frame = CGRectMake(0, 36 - underlineH, KScreenW, underlineH);
        underline.backgroundColor = colorWithA(75, 75, 75,0.2);
        [_titleView addSubview:underline];
        _titleView.backgroundColor = [UIColor whiteColor];
    }
    
    
    
    return _titleView;
}





@end
